<!-- 制片人 -->
<!-- 制片人 -->
<template>
  <el-dialog v-model="dialogVisible" width="400" title="制片人" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <el-form ref="elFormRef" :model="formData" labelPosition="top" :rules="rules" scrollToError>
      <el-form-item label="头像" labelWidth="7em" prop="">
        <!-- 头像 -->
        <rest-upload-qn
          v-model="formData.staffHeadImage"
          folder="avg-duration/avatar"
          :width="90"
          :height="90"
          :accept="['.png', '.jpg']"
          :limit="1"
          :maxImageSize="1024 * 5"
          :afterSelectFile="openCropper"
          @change="staffHeadImageChange"
        ></rest-upload-qn>
      </el-form-item>
      <el-form-item label="制片人名称" labelWidth="7em" prop="name">
        <bubble-select-local
          v-model="formData.name"
          labelKey="staffName"
          valueKey="staffId"
          allowCreate
          :list="cinemanufacturerList"
          placeholder="请输入演员名称"
        >
          <template #default="{ item }">
            <el-option :label="item.staffName" :value="item.staffId" @click="cinemanufacturerChange(item)"></el-option>
          </template>
        </bubble-select-local>
      </el-form-item>
      <el-form-item label="制片人性别" labelWidth="7em" prop="staffSex">
        <box-from-border>
          <el-radio-group v-model="formData.staffSex">
            <el-radio label="男士" :value="1"></el-radio>
            <el-radio label="女士" :value="2"></el-radio>
          </el-radio-group>
        </box-from-border>
      </el-form-item>
      <el-form-item labelWidth="0em">
        <div style="width: 100%; padding-top: 20px">
          <el-button style="width: 100%" type="success" @click="submit">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
    <rest-image-cropper ref="restImageCropperRef"></rest-image-cropper>
  </el-dialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus';
  import { type Cinemanufacturer, type CinemanufacturerItem, getCinemanufacturerListAxios } from '@/api/drama-management';
  type $ShowData = {
    /** 制片人信息 */
    producerInfo: Cinemanufacturer | null;
    /** 审核后的回调 */
    addCallBack?: (data: Cinemanufacturer) => void;
  };
  let addCallBack: $ShowData['addCallBack'] = undefined;

  const dialogVisible = ref(false);
  const restImageCropperRef: $RefComp<'RestImageCropper'> = ref(null);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const cinemanufacturerList = ref<CinemanufacturerItem[]>([]);

  const formData = reactive<Cinemanufacturer>({
    name: '',
    staffType: 2,
    staffHeadImage: '',
    staffSex: 1,
  });

  const rules: FormRules<Cinemanufacturer> = {
    staffHeadImage: [{ required: true, type: 'string', message: '请上传制片人头像', trigger: ['blur', 'change'] }],
    name: [
      { required: true, type: 'string', message: '请输入制片人演名称', trigger: ['blur', 'change'] },
      { required: true, min: 1, type: 'string', message: '制片人名称不合法', trigger: ['blur', 'change'] },
    ],
    staffSex: [
      { required: true, type: 'number', message: '请选择制片人性别', trigger: ['blur', 'change'] },
      { type: 'enum', enum: [1, 2], message: `制片人性别不合法`, trigger: ['blur', 'change'] },
    ],
  };

  /**
   * 提交
   */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      hide();
      typeof addCallBack === 'function' && addCallBack(JSON.parse(JSON.stringify(formData)));
    } catch (error) {
      console.log('error====', error);
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  async function show(data: $ShowData) {
    formData.name = data.producerInfo?.name || '';
    formData.staffType = data.producerInfo?.staffType ?? 2;
    formData.staffSex = data.producerInfo?.staffSex ?? 1;
    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    dialogVisible.value = true;

    const { data: cfList } = await getCinemanufacturerListAxios();
    formData.staffHeadImage = data.producerInfo?.staffHeadImage || '';
    cinemanufacturerList.value = cfList;
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 填充信息 */
  function cinemanufacturerChange(val: CinemanufacturerItem) {
    if (val.staffHeadImage) {
      formData.staffHeadImage = val.staffHeadImage;
    }
    formData.name = val.staffName;
    formData.staffSex = val.staffSex;
  }

  /** 头像改变 */
  function staffHeadImageChange(list: unknown[]) {
    if (!list.length) {
      formData.staffHeadImage = '';
    }
  }

  /** 打开裁剪框 */
  function openCropper(files: File[]): Promise<File[]> {
    return new Promise((resolve, reject) => {
      const file = files[0];
      if (file) {
        restImageCropperRef.value?.show({
          file,
          croppedCanvasOptions: {
            fillColor: '#ffffff',
            maxWidth: 240,
            maxHeight: 240,
          },
          fail: () => {
            reject(null);
          },
          success: (res: File) => {
            resolve([res] as File[]);
          },
        });
      } else {
        resolve(files);
      }
    });
  }
  defineExpose({ show, hide });
</script>
